//转化省标数据内容
var pageii = null;
var baseURL = "../../";
var problemsNum = 1;
var templetId = "";
$(function () {
    $("#inspectorsPerson").css("display", "none");
    $("#unitResponsiblePerson").css("display", "block");
    $("#inspectorsPolice").css("display", "block");
    $(".problem-title").css("display", "block");
    $(".add-img-div").css("display", "block");
    $(".problems").css("display", "block");
    $(".add-img").on('click', function () {
        addProblems()

    });

    getDdcdws();
    getDcrys();
    getBdcrys(-1);
    getJcxs($("#recordType").val() - 2);
    getSupervisionPersonList();
    init(1)
    photoVueCheck(1)

})

function checkData() {
    if ($("#bdcdws").val() == -1 || $("#bdcdws").val() == undefined || $("#bdcdws").val() == null || $("#bdcdws").val() == '') {
        layer.msg("被督察单位不能为空");
        return false;
    }
    if ($("#recordType").val() == -1 || $("#recordType").val() == undefined || $("#recordType").val() == null || $("#recordType").val() == '') {
        layer.msg("督察方式不能为空");
        return false;
    }
    if ($("#dcTime").val() == -1 || $("#dcTime").val() == undefined || $("#dcTime").val() == null || $("#dcTime").val() == '') {
        layer.msg("督察时间不能为空");
        return false;
    }
    if ($("#dcry").val() == -1 || $("#dcry").val() == undefined || $("#dcry").val() == null || $("#dcry").val() == '') {
        layer.msg("督察人员不能为空");
        return false;
    }
    return true;

}

function saveFirstKind() { debugger;
    if (!checkData()) {
        return;
    }

    var submitDate = new Object();
//    var formData = new FormData();
    submitDate.dcfs = $("#recordType").val();
    submitDate.dcdwId = $("#dcdwId").val();
    submitDate.createUser = $("#createUserId").val();
    submitDate.toDcdwId = $("#bdcdws").val();
    submitDate.templetId = templetId;
    submitDate.dcry = $('#dcry').val();
    submitDate.dcTime = $('#dcTime').val().replace(/-/g, "/");

    submitDate.supervisionQuestionBeanList = [];

    for (var i = 1; i < problemsNum + 1; i++) {
        if (!checkProblem(i)) {
            return;
        }
        var SupervisionQuestionBean = new Object();
        SupervisionQuestionBean.superviseImageEntityList = [];
        SupervisionQuestionBean.questionId = $("#jcxm" + i).val();//检查项目
        SupervisionQuestionBean.toDcry = $("#bdcry" + i).val();//被督察人员
        SupervisionQuestionBean.qksm = $("#qksm" + i).val();//情况说明
        SupervisionQuestionBean.zglx = $("#rectificationType" + i).val();//整改类型
        SupervisionQuestionBean.zgjzrq = $("#zgts" + i).val();//整改天数

        var b = $("#fileListLength"+i).val();
        if(b != 0){
            for (var a = 1; a < (b-0+1); a++ ){
                var SuperviseImageEntity = new Object();
                SuperviseImageEntity.picName = getFileName($("#file_"+i+"_"+a).val());
                SuperviseImageEntity.picUrl = $("#file_"+i+"_"+a).val();
                SuperviseImageEntity.QF = "0";
                SupervisionQuestionBean.superviseImageEntityList.push(SuperviseImageEntity);
            }
        }
        submitDate.supervisionQuestionBeanList.push(SupervisionQuestionBean);
    }
        console.log(submitDate);
        console.log(JSON.stringify(submitDate));
        $.ajax({
            type: "POST",
            url: baseURL + 'app/sceneSupervision/superviseSubmit',
            dataType: 'json',
            data: {json: JSON.stringify(submitDate)},
            contentType: "application/x-www-form-urlencoded",
            success: function (data) {
                if (data.code == '0') {
                    parent.layer.msg("新增督查记录成功！");
                    reste();
                }
            }
        });

}

//获取文件名
function getFileName(o) {
     var pos = o.lastIndexOf("/");
    return o.substring(pos + 1);
}

//关闭当前窗口
function reste() {
    parent.layer.close(parent.vm.index);
}

//时间日期转换成string
function data_string(str, value) {
    if (value == "yyyy-MM-dd hh:mm:ss") {
        var d = eval('new ' + str.substr(1, str.length - 2));
        var ar_date = [d.getFullYear(), d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds()];
        for (var i = 0; i < ar_date.length; i++) ar_date[i] = dFormat(ar_date[i]);
        return ar_date.slice(0, 3).join('-') + ' ' + ar_date.slice(3).join(':');

        function dFormat(i) {
            return i < 10 ? "0" + i.toString() : i;
        }
    }
    else if (value == "yyyy-MM-dd") {
        var d = eval('new ' + str.substr(1, str.length - 2));
        var ar_date = [d.getFullYear(), d.getMonth() + 1, d.getDate()];
        for (var i = 0; i < ar_date.length; i++) ar_date[i] = dFormat(ar_date[i]);
        return ar_date.join('-');

        function dFormat(i) {
            return i < 10 ? "0" + i.toString() : i;
        }
    }
}

/*获取被督察单位数据*/
var bdcdwsSelectHtml = ""

function getDdcdws() {
    $.ajax({
        type: "GET",
        url: baseURL + '/business/supervise/getbdcdw',
        contentType: "application/json",
        success: function (data) {
            bdcdwsSelectHtml = "<option value='-1'></option>";
            for (var i = 0; i < data.length; i++) {
                bdcdwsSelectHtml += "<option value=" + data[i].deptId + ">" + data[i].name + "</option>";
            }
            $("#bdcdws").html(bdcdwsSelectHtml);
            $('#bdcdws').chosen({
                no_results_text: "没有找到",
                allow_single_deselect: true
            });
        }
    });
}

/*获取督察人员数据*/
var dcrySelectHtml = ""

function getDcrys() {

    $.ajax({
        type: "GET",
        url: baseURL + '/business/supervise/getSupervisePersons?flag=1',
        contentType: "application/json",
        success: function (data) {
            dcrySelectHtml = "<option value='-1'></option>";
            for (var i = 0; i < data.length; i++) {
                dcrySelectHtml += "<option value=" + data[i].NAME + ">" + data[i].NAME + "</option>";
            }
            $("#dcry").html(dcrySelectHtml);
            $('#dcry').chosen({
                no_results_text: "没有找到",
                allow_single_deselect: true
            });
        }
    });
}

/*获取被督察人员数据*/
var bdcrySelectHtml = ""

function getBdcrys(deptId) {
    if (deptId != -1) {
        debugger

        $.ajax({
            type: "GET",
            url: baseURL + '/business/supervise/getSupervisePersons?deptId=' + deptId,
            contentType: "application/json",
            success: function (data) {

                bdcrySelectHtml = "<option value='-1'></option>";
                for (var i = 0; i < data.length; i++) {
                    bdcrySelectHtml += "<option value=" + data[i].NAME + ">" + data[i].NAME + "</option>";
                }

                $('#bdcry1').chosen("destroy")
                $("#bdcry1").html(bdcrySelectHtml);
                $('#bdcry1').chosen({
                    no_results_text: "没有找到",
                    allow_single_deselect: true
                });
            }
        });
    } else {
        $('#bdcry1').chosen();
    }


}

/*获取被检查项数据*/
var jcxmSelectHtml = ""

function getJcxs(flag) {

    $.ajax({
        type: "GET",
        url: baseURL + '/business/supervise/getCheckList?num=' + flag,
        contentType: "application/json",
        success: function (res) {
            $("#jcxm1").html("");
            var data = res.data;
            templetId = res.templetId;
            jcxmSelectHtml = "<option value='-1'></option>";
            for (var i = 0; i < data.length; i++) {
                jcxmSelectHtml += "<option value=" + data[i].id + ">" + data[i].name + "</option>";
            }
            $('#jcxm1').chosen("destroy")
            $("#jcxm1").html(jcxmSelectHtml);
            $('#jcxm1').chosen({
                no_results_text: "没有找到",
                allow_single_deselect: true
            });
        }
    });
}

function updateJcxList(val) {

    getJcxs(val - 2);
    $("#inspectorsPerson").css("display", "none");
    $("#unitResponsiblePerson").css("display", "block");
    $("#inspectorsPolice").css("display", "block");
    $(".problem-title").css("display", "block");
    $(".add-img-div").css("display", "block");
    $(".problems").css("display", "block");

}

function init(num) {

    $(".add-scene-check" + num).on('click', function () {
        var dataId = $(this).attr("data-id")
        var dataV = $(this).attr("data-v")
        if (dataV == 5) {
            layer.msg("最多只能上传4张照片");
            return
        }
        addSceneImg(dataId, dataV)

    });
    $(".delete-scene-check" + num).on('click', function () {
        if (problemsNum == 1){
            layer.msg("记录问题数不能为0");
        }else{
            $("div#problemsDiv"+num).remove();//移除div
            if(problemsNum > num){
                for (var i = (num+1); i < (problemsNum + 1); i++) {
                    $("div#problemsDiv"+i+" .problem-span").text("问题"+num);//修改问题序号
                    $("#problemsDiv"+i).attr("id","problemsDiv"+num);
                    $("#bdcry"+i).attr("id","bdcry"+num);
                    $("#jcxm"+i).attr("name","jcxm"+num);
                    $("#jcxm"+i).attr("id","jcxm"+num);
                    $("#qksm"+i).attr("id","qksm"+num);
                    $("#zgts"+i).attr("id","zgts"+num);
                    $("#rectificationType"+i).attr("onchange","rectificationTypeSelect(this.options[this.options.selectedIndex].value,"+num+")")
                    $("#rectificationType"+i).attr("id","rectificationType"+num);
                    $("#deleteSceneImg"+i).attr("class","delete-scene-img delete-scene-check"+num)
                    $("#deleteSceneImg"+i).attr("data-id",num)
                    $("#deleteSceneImg"+i).attr("id","deleteSceneImg"+num);
                    $("#imgMargin"+i).attr("id","imgMargin"+num);
                    $("#timeLimit"+i).attr("id","timeLimit"+num);
                    $("#fileListLength"+i).attr("id","fileListLength"+num);
                    $("#file_"+i+"_1").attr("id","file_"+num+"_1");
                    $("#file_"+i+"_2").attr("id","file_"+num+"_2");
                    $("#file_"+i+"_3").attr("id","file_"+num+"_3");
                    $("#file_"+i+"_4").attr("id","file_"+num+"_4");

                    num++;
                }
            }
               problemsNum--;
       }
    });
}

/**
 * 插件加载
 */
function selectPlugInUnit(num) {
    $('#jcxm' + num).chosen({
        no_results_text: "没有找到",
        allow_single_deselect: true, max_selected_options: 1
    });
    $('#bdcry' + num).chosen({
        no_results_text: "没有找到",
        allow_single_deselect: true
    });
}

function addSceneImg(dataId, dataV) {
    var dataVAdd = parseInt(dataV) + 1
    var html = " <div class=\"img-margin\"id=\"sceneImgDiv_" + dataId + "_" + dataVAdd + "\">" +
        "                        <input type=\"file\" id=\"sceneImgDefaultFile_" + dataId + "_" + dataVAdd + "\" data-id=\"" + dataId + "_" + dataVAdd + "\"" +
        "                               onchange=\"updateFile(this,'" + dataId + "_" + dataVAdd + "')\"" +
        "                               hidden />" +
        "                        <label  for=\"sceneImgDefaultFile_" + dataId + "_" + dataVAdd + "\">" +
        "                    <img id=\"sceneImgDefault_" + dataId + "_" + dataVAdd + "\" data-id=\"" + dataId + "_" + dataVAdd + "\" class=\"scene-img-default \" form src=\"/inspect-manage-back/statics/plugins/index/images/index/u347.png\">" +
        "                        </label>" +
        "" +
        "                    </div>";

    $("#imgMargin" + dataId).append(html)
    $("#deleteSceneImg" + dataId).attr("data-v", dataVAdd)
    $("#addSceneImg" + dataId).attr("data-v", dataVAdd)

}

function rectificationTypeSelect(val, num) {
    if (val == 1) {//限时整改需要输入天数
        $("#timeLimit" + num).css("visibility", "visible");
    } else {
        $("#timeLimit" + num).css("visibility", "hidden");
    }
}

function getSupervisionPersonList() {

    var html = "<input name='checkPerson' type='checkbox' value='1'/><span id='span1' style='display: inline-block;width: 80px'>周</span>" +
        "<input name='checkPerson' type='checkbox' value='2'/><span id='span2' style='display: inline-block;width: 80px'>周2</span>";

    $("#supervisionPerson").html(html);

}

//选择督察人员
function checkedSupervisionPerson() {
    pageii = layer.open({
        title: ['督察人员'],
        // title : "发布任务",
        type: 1,
        fixed: true,
        //shadeClose : true,
        area: ["420px", "20%"],
        btn: ['确定'],
        content: $("#supervisionPerson"),
        yes: function (index, layero) {
            var inspectPersonSpan = "";
            $('input[name="checkPerson"]:checked').each(function () {//遍历每一个名字为interest的复选框，其中选中的执行函数
                var id = $(this).val();
                inspectPersonSpan += $("#span" + id).text() + ",";//拼接检查人
                // chk_value.push($(this).val());//将选中的值添加到数组chk_value中

            });
            $("#inspectPersonSpan").text(inspectPersonSpan);
            layer.close(index);
        }
    });
}

//替换
function updateFile(obj, type) {
    var objUrl = getObjectURL(obj.files[0]);

    $("#sceneImgDefault_" + type).attr("src", objUrl);

}

function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

function recordTypeSelect(val) {
    if (val == 1) {
        $("#inspectorsPerson").css("display", "block");
        $("#unitResponsiblePerson").css("display", "none");
        $("#inspectorsPolice").css("display", "none");
        $(".problem-title").css("display", "none");
        $(".problems").css("display", "none");
        $(".add-img-div").css("display", "none");
    } else {
        $("#inspectorsPerson").css("display", "none");
        $("#unitResponsiblePerson").css("display", "block");
        $("#inspectorsPolice").css("display", "block");
        $(".problem-title").css("display", "block");
        $(".add-img-div").css("display", "block");
        $(".problems").css("display", "block");
    }
}

function checkProblem(n) {

    if ($("#jcxm" + n).val() == -1 || $("#jcxm" + n).val() == undefined || $("#jcxm" + n).val() == null || $("#jcxm" + n).val() == '') {
        layer.msg("问题" + n + "检查项目不能为空");
        return false;
    }
    if ($("#rectificationType" + n).val() == -1 || $("#rectificationType" + n).val() == undefined || $("#rectificationType" + n).val() == null || $("#rectificationType" + n).val() == '') {
        layer.msg("问题" + n + "整改类型不能为空");
        return false;
    }
    if ($("#qksm" + n).val() == undefined || $("#qksm" + n).val() == null || $("#qksm" + n).val() == '') {
        layer.msg("问题" + n + "情况说明不能为空");
        return false;
    }
    if ($("#zglx" + problemsNum).val() == 1) {//限时整改
        if ($("#zgts" + problemsNum).val() == undefined || $("#zgts" + problemsNum).val() == null || $("#zgts" + problemsNum).val() == '') {
            layer.msg("问题" + problemsNum + "限时整改时整改天数不能为空");
            return false;
        }
    }
    return true;
}

function addProblems() {
    var flag = checkProblem(problemsNum);
    if (flag) {
        problemsNum++;
        var html = "<div id='problemsDiv" + problemsNum + "'>" +
            " <li class=\"clearfix problem-title\"   >" +
            "                <span class=\"clearfix problem-span\"> 问题" + problemsNum + "</span>" +
            "                <img data-id='" + problemsNum + "' data-v='1'id='deleteSceneImg" + problemsNum + "' class='delete-scene-img delete-scene-check" + problemsNum + "' src='/inspect-manage-back/statics/plugins/index/images/index/u349.png'> " +
            "        </li>" +
            "        <li class=\"center-form-item3 clearfix \"  id=\"inspectorsPolice\">" +
            "            <label class=\"center-form-label4\">被督察民警：</label>" +
            "            <div class=\"center-form-content4\">" +
            "                <select multiple data-placeholder=\"请选择被督察民警\"  class=\"chosen-select\" name=\"bdcry\" id=\"bdcry" + problemsNum + "\">" +
            bdcrySelectHtml +
            "                </select>" +
            "            </div>" +
            "        </li>";

        html += "        <li class=\"center-form-item2 clearfix\">" +
            "            <label class=\"center-form-label2\">检查项目：</label>" +
            "            <div class=\"center-form-content2\">" +
            "                <select data-placeholder=\"请选择检查项目\"  class=\"chosen-select\" name=\"jcxm" + problemsNum + "\"  id=\"jcxm" + problemsNum + "\">" +
            jcxmSelectHtml +
            "                </select>" +
            "            </div>" +
            "        </li>" +
            "" +
            "        <li class=\"center-form-item4 clearfix\">" +
            "            <label class=\"center-form-label5\">情况说明：</label>" +
            "            <div class=\"center-form-content5\">" +
            "                <textarea id=\"qksm" + problemsNum + "\" class=\"center-from-input\" style=\"overflow-x: hidden;overflow-y: visible; resize:none; width: 93%;height: 100px\"></textarea>" +
            "            </div>" +
            "        </li>" +
            "        <li class=\"center-form-item2 clearfix\">" +
            "            <label class=\"center-form-label2\">整改类型：</label>" +
            "            <div class=\"center-form-content2\">" +
            "                <select  class=\"center-from-select\" id=\"rectificationType" + problemsNum + "\"" +
            "                onchange=\"rectificationTypeSelect(this.options[this.options.selectedIndex].value," + problemsNum + ")\">" +
            "                    <option value=\"-1\"></option>" +
            "                    <option value=\"0\">现场纠正</option>" +
            "                    <option value=\"1\">限时整改</option>" +
            "                    <option value=\"2\">无问题</option>" +
            "                </select>" +
            "            </div>" +
            "        </li>" ;
            html += "        <li class=\"center-form-item2 clearfix\"  id=\"timeLimit" + problemsNum + "\" style=\"visibility:hidden\">" +
                                "            <label class=\"center-form-label2\">时间天数：</label>" +
                                "            <div class=\"center-form-content2\">" +
                                "                <input id=\"zgts" + problemsNum + "\" type=\"text\"" +
                                "                       placeholder=\" 请输入天数\"" +
                                "                       class=\"center-from-input1\" maxlength=\"2\"/>" +
                                "                <span style=\"font-size: 18px;color:red\">最大30天</span>" +
                                "            </div>" +
                                "        </li>" +
            " <li class='center-form-item clearfix'> " +
                    "                <label class='center-form-label'>现场照片：</label> " +
                    "                <div class='center-form-content4'> " +
                    "                    <div id='imgMargin" + problemsNum + "'>" +
                    "                    <input type=\"hidden\" id='fileListLength" +problemsNum +"' value=\"0\"/> "+
                    "                    <input type=\"hidden\" id='file_" +problemsNum+ "_1'/>" +
                    "                    <input type=\"hidden\" id='file_" +problemsNum+ "_2'/> "+
                    "                    <input type=\"hidden\" id='file_" +problemsNum+ "_3'/> "+
                    "                    <input type=\"hidden\" id='file_" +problemsNum+ "_4'/> "+
                    "<el-upload " +
                    "                                        action=\"/inspect-manage-back/app/common/file/uploadFile\" " +
                    "                                        list-type=\"picture-card\" " +
                    "                                        limit=\"4\" " +
                    "                                        :on-preview=\"handlePictureCardPreview\" " +
                    "                                        :before-upload=\"beforeAvatarUpload\" " +
                    "                                        :on-success=\"handleOnSuccess\" " +
                    "                                        :on-remove=\"handleRemove\">" +
                    "                                    <!--<i class=\"el-icon-plus\"></i>-->" +
                    "                                    <el-button size=\"small\" type=\"primary\">点击上传</el-button>" +
                    "                                    <div slot=\"tip\" class=\"el-upload__tip\">只能上传jpg/png文件，且不超过500kb</div>" +
                    "                                </el-upload> " +
                    // "  <el-upload　" +
                    // "                                    class=\"upload-demo\"" +
                    // "                                    action=\"https://jsonplaceholder.typicode.com/posts/\"" +
                    // "                                    :on-preview=\"handlePreview\"" +
                    // "                                    :on-remove=\"handleRemove\"" +
                    // "                                    :file-list=\"fileList2\"" +
                    // "                                    limit=\"4\"" +
                    // "                                    list-type=\"picture\">" +
                    // "                                <el-button size=\"small\" type=\"primary\">点击上传</el-button>" +
                    // "                                <div slot=\"tip\" class=\"el-upload__tip\">只能上传jpg/png文件，且不超过500kb</div>" +
                    // "                            </el-upload>" +
                    // "                    <div class='img-margin'id='sceneImgDiv_" + problemsNum + "_1'> " +
                    // "                        <input type='file' id='sceneImgDefaultFile_1_1' data-id='" + problemsNum + "_1' " +
                    // "                               onchange='updateFile(this,'" + problemsNum + "_1')' " +
                    // "                               hidden /> " +
                    // "                        <label  for='sceneImgDefaultFile_" + problemsNum + "_1'> " +
                    // "                    <img id='sceneImgDefault_" + problemsNum + "_1' data-id='" + problemsNum + "_1' class='scene-img-default' form src='/inspect-manage-back/statics/plugins/index/images/index/u347.png'> " +
                    // "                        </label> " +
                    // " " +
                    // "                    </div> " +
                    "                    </div> " +
                    // "                    <div > " +
                    // "                        <img  data-id='" + problemsNum + "' data-v='1' id='addSceneImg" + problemsNum + "' class='add-scene-img add-scene-check" + problemsNum + "' src='/inspect-manage-back/statics/plugins/index/images/index/u348.png'> " +
                    // "                        <img data-id='" + problemsNum + "' data-v='1'id='deleteSceneImg" + problemsNum + "' class='delete-scene-img delete-scene-check" + problemsNum + "' src='/inspect-manage-back/statics/plugins/index/images/index/u349.png'> " +
                    // "                    </div> " +
                    "                </div> " +
                    "            </li>" +
                            "</div>";

        $(".problems").append(html);
        init(problemsNum)
        selectPlugInUnit(problemsNum)
        photoVueCheck(problemsNum)
    }

}
function photoVueCheck(num) {
    var vm = new Vue({
        el: '#imgMargin'+num,
           data() {
        return {
            dialogImageUrl: '',
            dialogVisible: false
        };
    },
    methods: {
    beforeAvatarUpload(file) {
        		debugger;
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                var r = /[+/?%=&#]/;
                var isZf = true;
                if(file.name.search(r) > -1){
                    layer.msg("上传图片名包含非法字符!");
                    isZf = false;
                }

                if (!isJPG) {
                	layer.msg('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                	layer.msg('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M && isZf;
              },
        handleRemove(file, fileList) {
            console.log(fileList)
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleOnSuccess(response, file, fileList){
            console.log(fileList)
            $("#fileListLength"+num).val(fileList.length);
            for (var i = 0; i<fileList.length;i++){
                $("#file_"+num+"_"+(i+1)).val(fileList[i].response.filePath)
            }
        },
    }
    })
}
